package cn.com.netedge.iot.frontend.comm;

import cn.com.netedge.iot.common.constants.CacheKeyConstants;
import cn.com.netedge.iot.common.constants.Globals;
import cn.com.netedge.iot.common.utils.DateUtil;
import cn.com.netedge.iot.common.utils.FrontEndUtil;
import cn.com.netedge.iot.common.utils.RedisUtil;
import cn.com.netedge.iot.common.utils.StringUtil;
import cn.com.netedge.iot.frontend.comm.constants.AppConstant;
import cn.com.netedge.iot.frontend.comm.nio.FeTcpServer;
import cn.com.netedge.iot.frontend.comm.utils.JmsMsgUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.scheduling.annotation.EnableScheduling;

import java.util.Date;

@SpringBootApplication(exclude = {RedisAutoConfiguration.class})
@ComponentScan(basePackages = {"cn.com.netedge.iot.fe.comm","cn.com.netedge.iot.protocol","cn.com.netedge.iot.common.utils"})
@EnableScheduling
public class FeCommApplication {
    private static Logger logger = LoggerFactory.getLogger(FeCommApplication.class);

    public static void main(String[] args) {
        ApplicationContext context = SpringApplication.run(FeCommApplication.class, args);
        AppConstant.APP_CONTEXT = context;

        initApp(context);
    }
    public static void initApp(ApplicationContext context) {
        logger.info("app start...");

        //注册前置存活信息
        AppConstant.machineName = CacheKeyConstants.KEY_FRONTEND_COMM_MACHINE + FrontEndUtil.getMachineNo();

        Date now = new Date();
        RedisUtil.hset(CacheKeyConstants.KEY_FRONTEND_COMM_MACHINE + "machine_map", AppConstant.machineName, DateUtil.DateToLongStr(now));

        JmsMsgUtil jmsMsgUtil = AppConstant.APP_CONTEXT.getBean(JmsMsgUtil.class);
        JmsMsgUtil.setAppName(Globals.APP_FRONTEND_COMM);
        jmsMsgUtil.subscribeQueues();

        String configPath = System.getProperty("configPath");
        logger.info("configPath:{}", configPath);
        if (!StringUtil.isEmpty(configPath)) {//本地版
            AppConstant.LOCAL_MODE = true;
        }

        //打开TCP通道
        FeTcpServer fecTcpServer = context.getBean(FeTcpServer.class);
        Thread tcpThread = new Thread(fecTcpServer);
        tcpThread.start();
        logger.info("打开TCP通道");

        if (StringUtil.isEmpty(configPath)) {//云平台
            logger.info("进入 云平台模式");
            return;
        }
        logger.info("进入 本地版模式");
        AppConstant.LOCAL_MODE = true;
    }

}
